package cn.kongwg.service.impl;

import cn.kongwg.bean.*;
import cn.kongwg.dao.BookDao;
import cn.kongwg.dao.OrderDao;
import cn.kongwg.dao.OrderItemDao;
import cn.kongwg.dao.impl.BookDaoImpl;
import cn.kongwg.dao.impl.OrderDaoImpl;
import cn.kongwg.dao.impl.OrderItemDaoImpl;
import cn.kongwg.service.OrderService;

import java.util.Date;
import java.util.Map;

/**
 * @author kongwg
 * @create 2021-02-01 19:20
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {

        String orderId = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        orderDao.saveOrder(order);

        int a = 12 / 0;
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {

            CartItem value = entry.getValue();

            OrderItem orderItem = new OrderItem(null, value.getName(), value.getPrice(), value.getCount(), value.getTotalPrice(), orderId);
            orderItemDao.saveOrderItem(orderItem);



            Book book = bookDao.queryBookById(value.getId());

            book.setSales(book.getSales() + value.getCount());
            book.setStock(book.getStock() - value.getCount());
            bookDao.updateBook(book);
        }

        cart.clear();

        return orderId;
    }
}
